﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using System.Xml;
using BussisnesException;

namespace Services
{
    public class LoginService
    {

        public String login(XmlElement response)
        {
            UserService service = new UserService();
            User u = parseUser(response);

            String result = "";
            try
            {
                u = service.findByPK(u.Username);
            }
            catch (ObjectNotFoundException e) {
                service.create(u);        
            }
            TweetService tweetService = new TweetService();
            result = tweetService.getAllTweetsJson(u.Username);
            return result;
        }

        private User parseUser(XmlElement response)
        {
            XmlNode profile = response.FirstChild;
            XmlNode providerName = profile.FirstChild;
            XmlNode email = providerName.NextSibling.NextSibling;
            User u = new User();
            u.Email = email.InnerText;
            XmlNode name = email.NextSibling.NextSibling;
            u.Username = name.InnerText;
            XmlNode img = name.NextSibling.NextSibling.NextSibling;
            u.ImagePath = img.InnerText;
            return u;
        }
    }
}
